package com.lee.demonacosclient.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName NacosWeightRule
 * @Description 让 loadBalancer 支持 nacos的权重机制
 * @Author leejiliang
 * @DateTime 2020/9/19 10:15 PM
 * @Version 1.0
 */
public class NacosWeightRule extends AbstractLoadBalancerRule {

	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;
	@Autowired
	private NacosServiceManager nacosServiceManager;
	@Override
	public void initWithNiwsConfig(IClientConfig iClientConfig) {

	}

	@Override
	public Server choose(Object o) {
		BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
		String name = loadBalancer.getName();
		NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());

		try {
			Instance instance = namingService.selectOneHealthyInstance(name);
			return new NacosServer(instance);
		} catch (NacosException e) {
			e.printStackTrace();
		}
		return null;
	}
}
